/*
 * Copyright (c) 2017. danlu.com Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.dlware;

import com.danlu.lib.net.func.TransformErrorFunc;

import cn.com.dhc.danlu.dlware.net.func.ServerProtocolFunc;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.response.base.BaseResponseWrapper;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * author: wuhaiyang(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-02-06 下午2:30<br/>
 * <p>
 * Rx 操作符工具类
 * </p>
 */
public class OperatorUtils {
    public static <R extends BaseResponse> Observable.Transformer<BaseResponseWrapper<R>, R> defaultSchedulers() {
        return new Observable.Transformer<BaseResponseWrapper<R>, R>() {
            @Override
            public Observable<R> call(Observable<BaseResponseWrapper<R>> tObservable) {
                //map -> 处理服务器协议异常
                // onErrorResumeNext -> 对异常进行翻译，UI层不做任何判断直接予以显示
                return convertThread(tObservable.map(new ServerProtocolFunc<R>()).onErrorResumeNext(new TransformErrorFunc<R>()));
            }
        };
    }

    public static <R extends BaseResponse> Observable.Transformer<BaseResponseWrapper<R>, R> proccessError() {
        return new Observable.Transformer<BaseResponseWrapper<R>, R>() {
            @Override
            public Observable<R> call(Observable<BaseResponseWrapper<R>> tObservable) {
                //map -> 处理服务器协议异常
                // onErrorResumeNext -> 对异常进行翻译，UI层不做任何判断直接予以显示
                return tObservable.map(new ServerProtocolFunc<R>()).onErrorResumeNext(new TransformErrorFunc<R>());
            }
        };
    }

    public static Observable convertThread(Observable observable) {
        return observable.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    }


    public static <R extends BaseResponse> Observable.Transformer<BaseResponseWrapper<R>, R> testSchedulers() {
        return new Observable.Transformer<BaseResponseWrapper<R>, R>() {
            @Override
            public Observable<R> call(Observable<BaseResponseWrapper<R>> tObservable) {
                return tObservable.map(new ServerProtocolFunc<R>())
                        .onErrorResumeNext(new Func1<Throwable, Observable<? extends R>>() {
                            @Override
                            public Observable<? extends R> call(Throwable throwable) {
                                return null;
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io());
            }
        };
    }

}
